import 'package:hrf_app/common/api/project/project.dart';
import 'package:hrf_app/common/models/notebook/MkNotebookModel.dart';
import 'package:hrf_app/common/models/notebook/SearchNotebookModel.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import '../../../bug_page_list/projectBugPage/model/searchProjectBugModel.dart';

class ProjectNotebookTabPage extends StatefulWidget {
  final String projectId;

  const ProjectNotebookTabPage({Key? key, required this.projectId})
      : super(key: key);

  @override
  State<ProjectNotebookTabPage> createState() => _ProjectNotebookTabPageState();
}

class _ProjectNotebookTabPageState extends State<ProjectNotebookTabPage> {
  late EasyRefreshController easyRefreshController;
  List<MkNotebookModel> projectBugList = [];
  SearchNotebookModel searchNotebookModel = SearchNotebookModel();

  @override
  Widget build(BuildContext context) {
    return _buildView();
  }

  Widget _buildView() {
    return Column(
      children: [
        Expanded(
            child: EasyRefresh(
          header: const ClassicHeader(
            dragText: '下拉刷新',
            armedText: '正在刷新...',
            processedText: '刷新完成',
            failedText: '刷新失败',
            noMoreText: '没有更多数据',
            showText: true,
            showMessage: true,
            messageText: '上次更新于 %T', // 默认时间格式
          ),
          footer: const ClassicFooter(
            dragText: '上拉加载更多',
            armedText: '释放加载更多',
            readyText: '准备加载更多',
            processingText: '正在加载...',
            processedText: '加载完成',
            failedText: '加载失败',
            noMoreText: '没有更多数据',
            showText: true,
            showMessage: true,
            messageText: '上次更新于 %T',
          ),
          controller: easyRefreshController,
          onRefresh: () async {
            print("下拉刷新逻辑");
            onRefresh();
          },
          onLoad: () async {
            print("上拉加载逻辑");
            onLoad();
          },
          child: ListView.builder(
              itemCount: projectBugList.length,
              itemBuilder: (context, index) {
                MkNotebookModel projectBugModel = projectBugList[index];
                return _buildItemView(projectBugModel);
              }),
        ))
      ],
    );
  }

  // 主视图
  Widget _buildItemView(   MkNotebookModel projectBugModel ) {
    return Container(
        margin: const EdgeInsets.all(8),
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: const [BoxShadow(color: Colors.grey, blurRadius: 0.3)],
          borderRadius: BorderRadius.circular(10),
        ),
        child: SizedBox(height: 100, child: _buildBugInfo(projectBugModel)));
  }

  Widget _buildBugInfo(MkNotebookModel projectBugModel) {

    List<Widget> columList = [];
    columList.add(buildInfoDetailTitle("标题：", projectBugModel.name!));
    columList.add(buildInfoDetailTitle("描述：", projectBugModel.contentDesc??""));
    columList.add(buildInfoDetailIDLeftRight(
        Row(
          children: [
            itemTitle(
              "创建人：",
            ),
            TDText(projectBugModel.creatorName??""),
          ],
        ),
        Row(
          children: [

          ],
        )));

    columList.add(
      buildInfoDetailTitle(
        "创建时间：",
        projectBugModel.createTime!,
      ),
    );
    return InkWell(
        onTap: () {
          onJumpToNotebook(projectBugModel.id);
        },
        child: Column(children: columList));
  }

//标题内容行
  Widget buildInfoDetailTitle(String title, String content) {
    return Row(
      children: [
        TDText(
          title,
          fontWeight: FontWeight.w700,
        ),
        Expanded(
          child: TDText(
            content,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    );
  }

//标题

  Widget buildInfoDetailIDLeftRight(Widget leftWidget, Widget rightWidget) {
    return Row(
      children: [
        Expanded(flex: 3, child: leftWidget),
        Expanded(flex: 3, child: rightWidget),
      ],
    );
  }

  Widget itemTitle(title) {
    return TDText(
      title,
      fontWeight: FontWeight.w700,
    );
  }
  void onRefresh() {
    searchNotebookModel.pageNum = 1;
    ProjectApi.getMkNotebookPageListApi(searchNotebookModel).then((res) {
      if (res["code"] == "00000") {
        List<MkNotebookModel> projectBugDetailList = [];
        for (var item in res["data"]["records"]) {
          projectBugDetailList.add(MkNotebookModel.fromJson(item));
        }

        setState(() {
          projectBugList = projectBugDetailList;
        });
        easyRefreshController.finishRefresh(IndicatorResult.success);
        easyRefreshController.resetFooter();
      }
    });
  }

  void onLoad() {
    searchNotebookModel.pageNum = searchNotebookModel.pageNum + 1;
    ProjectApi.getMkNotebookPageListApi(searchNotebookModel).then((res) {
      if (res["code"] == "00000") {
        List<dynamic> projectBugResList = [];
        projectBugResList = res["data"]["records"];
        if (projectBugResList.isEmpty) {
          easyRefreshController.finishLoad(IndicatorResult.noMore);
          searchNotebookModel.pageNum--;
        }
        if (projectBugResList.isNotEmpty) {
          List<MkNotebookModel> projectBugDetailList = projectBugList;
          for (var item in projectBugResList) {
            projectBugDetailList.add(MkNotebookModel.fromJson(item));
          }
          setState(() {
            projectBugList = projectBugDetailList;
          });
          easyRefreshController.finishLoad();
        }
      }
    });
  }

  @override
  void initState() {
    onInit();
    super.initState();
  }

  _initData() {
    searchNotebookModel.sourceId = widget.projectId;
    searchNotebookModel.sourceType = "PJ";
    getProjectBugListPage(searchNotebookModel);
  }
  void onInit() {
    easyRefreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );

    _initData();
  }

  getProjectBugListPage(params) {
    ProjectApi.getMkNotebookPageListApi(params).then((res) {
      if (res["code"] == "00000") {
        List<MkNotebookModel> projectBugDetailList = [];
        for (var item in res["data"]["records"]) {
          projectBugDetailList.add(MkNotebookModel.fromJson(item));
        }

        setState(() {
          projectBugList = projectBugDetailList;
        });
      }
    });
  }

  onJumpToNotebook(id) {
    Get.toNamed(RouteNames.notebookPreview, arguments: id);
  }
}
